import axios from 'axios'
import Qs from 'qs'
import {Message} from 'element-ui';
import router from "../router/router";
axios.defaults.baseURL = 'http://localhost:8081'
axios.defaults.withCredentials = true
axios.interceptors.response.use(success =>{
    if (success.status && success.status == 200 && success.data.status == 500){
        Message.error(success.data.msg)
        return
    }
    if (success.data.msg) {
        Message.success({message: success.data.msg})
    }
    return success.data;
},error => {
    if (error.response.status == 504 || error.response.status == 404) {
        Message.error({message: '服务器被吃了( ╯□╰ )'})
    } else if (error.response.status == 403) {
        Message.error({message: '权限不足，请联系管理员'})
    } else if (error.response.status == 401) {
        Message.error({message: '尚未登录，请登录'})
        router.replace('/')
    } else {
        if (error.response.data.msg) {
            Message.error({message: error.response.data.msg})
        } else {
            Message.error({message: '未知错误!'})
        }
    }
    return;
})
const request = function (url,method,params) {
    let config = {
        url: url,
        method: method,
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        }}
    if (method == 'get' || method == 'GET' || method == 'delete' || method == 'DELETE'){
        config.params = params
        config.paramsSerializer = function (params) {
            return Qs.stringify(params, { indices: false,skipNulls:true })
        }
    }else {
        config.data = Qs.stringify(params, { indices: false,skipNulls:true })
    }
    return axios.request(config)
}
const getRequest = function (url,params) {
    return axios.get(url,{params:params})
}

const postRequest = function (url,params) {
    return axios.post(url,params)
}

const putRequest = function (url,params) {
    return axios.put(url,params)
}

const deleteRequest = function (url,params) {
    return axios.delete(url,{params:params})
}



export {request,getRequest,postRequest,putRequest,deleteRequest}